package cn.itzzx.util;

import cn.itzzx.annotation.Service;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * TODO 写点注视啦
 *
 * @author Martin
 * @date 2020-05-04
 * @see 1.0
 */
@Service
public class ConnectionUtils {

    /**
     * 存储当前线程的连接，保证每个线程只有一个 Connection
     */
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public Connection getCurrentThreadConn() throws SQLException {
        /**
         * 判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
         */
        Connection connection = threadLocal.get();
        if (connection == null) {
            // 从连接池拿连接并绑定到线程
            connection = DruidUtils.getInstance().getConnection();
            // 绑定到当前线程
            threadLocal.set(connection);
        }
        return connection;

    }

}
